package com.xwq.smartgelleryhub.model.dto.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.xwq.smartgelleryhub.model.entity.User;
import com.xwq.smartgelleryhub.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户Excel导入监听器
 */
@Slf4j
public class UserImportListener extends AnalysisEventListener<ExcelUserDTO> {

    /**
     * 批量处理的阈值
     */
    private static final int BATCH_COUNT = 100;
    
    /**
     * 缓存的数据列表
     */
    private List<User> userList = new ArrayList<>();
    
    /**
     * 用户服务
     */
    private final UserService userService;
    
    /**
     * 成功导入的数量
     */
    private int successCount = 0;
    
    /**
     * 失败导入的数量
     */
    private int failCount = 0;
    
    /**
     * 默认密码
     */
    private static final String DEFAULT_PASSWORD = "12345678";
    
    public UserImportListener(UserService userService) {
        this.userService = userService;
    }
    
    @Override
    public void invoke(ExcelUserDTO data, AnalysisContext context) {
        log.info("解析到一条数据: {}", data);
        User user = new User();
        BeanUtils.copyProperties(data, user);
        
        // 设置默认密码
        if (!StringUtils.hasText(user.getUserPassword())) {
            String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
            user.setUserPassword(encryptPassword);
        }
        
        userList.add(user);
        
        // 达到BATCH_COUNT，需要批量处理一次，防止数据几万条数据在内存，容易OOM
        if (userList.size() >= BATCH_COUNT) {
            saveData();
            // 清理list
            userList.clear();
        }
    }
    
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 确保最后遗留的数据也被保存
        saveData();
        log.info("所有数据解析完成！成功导入: {}条, 失败: {}条", successCount, failCount);
    }
    
    /**
     * 保存数据到数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储到数据库！", userList.size());
        try {
            for (User user : userList) {
                try {
                    // 检查用户账号是否已存在
                    String userAccount = user.getUserAccount();
                    if (StringUtils.hasText(userAccount)) {
                        User existUser = userService.lambdaQuery().eq(User::getUserAccount, userAccount).one();
                        if (existUser != null) {
                            // 已存在，更新用户
                            user.setId(existUser.getId());
                            boolean success = userService.updateById(user);
                            if (success) {
                                successCount++;
                            } else {
                                failCount++;
                            }
                        } else {
                            // 不存在，新增用户
                            boolean success = userService.save(user);
                            if (success) {
                                successCount++;
                            } else {
                                failCount++;
                            }
                        }
                    } else {
                        log.error("用户账号不能为空");
                        failCount++;
                    }
                } catch (Exception e) {
                    log.error("保存用户数据失败: {}", e.getMessage(), e);
                    failCount++;
                }
            }
        } catch (Exception e) {
            log.error("批量保存用户数据异常: {}", e.getMessage(), e);
        }
        log.info("存储数据库成功！");
    }
    
    public int getSuccessCount() {
        return successCount;
    }
    
    public int getFailCount() {
        return failCount;
    }
} 